﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using Kindohm.KSynth.Library;

namespace Kindohm.KSynth.UI
{
    public class VoiceController
    {
        Dictionary<VoiceControls, Oscillator> registry;

        public VoiceController()
        {
            this.registry = new Dictionary<VoiceControls, Oscillator>();
        }

        public void RegisterOscillator(VoiceControls settings, Oscillator oscillator)
        {
            settings.SelectedWaveFormChanged += new EventHandler(settings_WaveformChanged);
            settings.PanChanged += new EventHandler(settings_PanChanged);
            settings.LevelChanged += new EventHandler(settings_LevelChanged);
            settings.PhaseChanged += new EventHandler(settings_PhaseChanged);
            settings.DetuneChanged += new EventHandler(settings_DetuneChanged);
            this.registry.Add(settings, oscillator);
        }

        void settings_DetuneChanged(object sender, EventArgs e)
        {
            VoiceControls settings = (VoiceControls)sender;
            Oscillator oscillator = this.registry[settings];
            oscillator.Detune = settings.Detune;
        }

        void settings_PhaseChanged(object sender, EventArgs e)
        {
            VoiceControls settings = (VoiceControls)sender;
            Oscillator oscillator = this.registry[settings];
            oscillator.PhaseShift = (uint)settings.Phase;
        }

        void settings_LevelChanged(object sender, EventArgs e)
        {
            VoiceControls settings = (VoiceControls)sender;
            Oscillator oscillator = this.registry[settings];
            oscillator.Attenuation = (int)settings.Level;
        }

        void settings_PanChanged(object sender, EventArgs e)
        {
            VoiceControls settings = (VoiceControls)sender;
            Oscillator oscillator = this.registry[settings];
            double percent = settings.Pan / 100d;
            oscillator.Pan = (short)((double)short.MaxValue * percent);           
        }

        void settings_WaveformChanged(object sender, EventArgs e)
        {
            VoiceControls settings = (VoiceControls)sender;
            Oscillator oscillator = this.registry[settings];
            if (settings.SelectedWaveForm != null)
            {
                oscillator.WaveForm = settings.SelectedWaveForm.WaveForm;
            }
            else
            {
                oscillator.WaveForm = null;
            }
        }
        
    }
}
